package xuecheng.framework.exception;

import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import xuecheng.framework.model.response.CommonCode;
import xuecheng.framework.model.response.ResponseResult;
import xuecheng.framework.model.response.ResultCode;

/**
 * 异常捕获类
 *
 * @author Simon
 */
@ControllerAdvice  //控制器增强
public class ExceptionCatch {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionCatch.class);

    //定义map，配置异常类型所对应的错误代码
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;
    //定义map的builder对象，去构建ImmutableMap
    private static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();

    static {
        //定义异常类型所对应的错误码
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALID_PARAM);
    }

    //捕获CustomException此类异常
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult customException(CustomException customException) {
        //记录日志
        logger.error("catch exception : {}", customException.getMessage());
        ResultCode resultCode = customException.getResultCode();
        return new ResponseResult(resultCode);
    }

    //捕获Exception此类异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exceptiion(Exception exception) {
        //记录日志
        logger.error("catch exception : {}", exception.getMessage());
        if (EXCEPTIONS == null) {
            EXCEPTIONS = builder.build();  //EXCEPTIONS构建成功
        }
        //从EXCEPTIONS中找到异常类型所对应的错误代码返回给用户，如果找不到则返回99999异常
        ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        if (resultCode != null) {
            return new ResponseResult(resultCode);
        } else {
          //返回99999异常
          return new ResponseResult(CommonCode.SERVER_ERROR);
        }
    }

}
